package cn.marinda.totipotentwar.runnable;

import cn.marinda.totipotentwar.TotipotentWar;
import cn.marinda.totipotentwar.global.ConfigData;
import cn.marinda.totipotentwar.utils.GameUtil;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitTask;

/**
 * 游戏运行的
 *
 * @author hwj
 * @date 2022/02/05
 */
public class GameRunnable extends BukkitRunnable {

    public int duration = 0;
    public  ConfigData configData;
    /**
     * 游戏运行的 进程器 是同步主线程。
     */
    public GameRunnable(ConfigData configData){
        this.configData = configData;
    }

    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see Thread#run()
     */
    @Override
    public void run() {
        //异步事件中带一个同步Runnable
        BukkitTask bukkitTask = new BukkitRunnable() {
            /**
             * When an object implementing interface <code>Runnable</code> is used
             * to create a thread, starting the thread causes the object's
             * <code>run</code> method to be called in that separately executing
             * thread.
             * <p>
             * The general contract of the method <code>run</code> is that it may
             * take any action whatsoever.
             *
             * @see Thread#run()
             */
            @Override
            public void run() {
                    //  如果人数要求已经满足！
                    if(GameUtil.onGameBol(configData)){
                        duration++;
                        if(configData.getJoinDuration() == duration){
                            GameUtil.startFlag = true;
                            World teleportWorld = Bukkit.getWorld(configData.getWorldName());
                            double x = configData.getX();
                            double y = configData.getY();
                            double z = configData.getZ();
                            for(Player player : GameUtil.playerGame){
                                //玩家传送至指定世界
                                player.teleport(new Location(teleportWorld,x,y,z));
                            }
                            System.out.println("success Result：" + String.valueOf(GameUtil.startFlag));
                            //取消当前
                            cancel();
                            TotipotentWar.bukkitTask.cancel();
                        }
                    }
                    //
                    System.out.println("人数：" + GameUtil.playerGame.size());

            }
        }.runTaskTimer(TotipotentWar.plugin,0,2000);

    }
}
